import { segment } from "oicq"
import data from '../model/XiuxianData.js'
import config from "../model/Config.js"
import plugin from '../../../lib/plugins/plugin.js'
import fs from "node:fs";
import common from "../../../lib/common/common.js";
import schedule from "node-schedule";
// import player_control from "./player_control.js"

/**
 * 定时任务
 */
export class xiuxiantask extends plugin {
    constructor() {
        super({
            name: '定时任务',
            dsc: '定时任务',
            event: 'message',
            priority: 300,
            rule: [
                {
                    reg: '^#查询任务是否完成$',
                    fnc: 'selectAction'
                }
            ]
        });

        //获取配置信息
        this.set = config.getdefSet('task', 'task')

        /** 定时任务查询人物动作结束时间 */
        this.task = {
            cron: '0 */2 * * * ?',
            name: '查询人物动作是否完成',
            fnc: () => this.selectAction()
        }


    }

    /** 查询人物动作是否完成 */
    async selectAction() {
        //获取缓存中人物列表
        let playerList = [];
        let files = fs
            .readdirSync("./plugins/xiuxian-emulator-plugin/resources/data/xiuxian_player")
            .filter((file) => file.endsWith(".json"));
        for (let file of files) {
            file = file.replace(".json", "");
            playerList.push(file);
        }
        for (let player_id of playerList) {
            let log_mag = "";//查询当前人物动作日志信息
            log_mag += "查询" + player_id + "是否有动作,";
            let action = await redis.get("xiuxian:player:" + player_id + ":action");
            if (action != null) {
                action = JSON.parse(action);
                let push_address;//消息推送地址

                let is_group = false;//是否推送到群
                if (action.hasOwnProperty("group_id")) {
                    if(isNotNull(action.group_id)){
                        is_group = true;
                        push_address = action.group_id;
                    }
                }

                if (action.is_jiesuan == "0") {//未结算的查询是否该结算
                    let end_time = action.end_time;//动作结束时间
                    let now_time = new Date().getTime();
                    if (now_time > end_time) {//结算时间小于当前时间开始计算
                        let msg=[segment.at(player_id)];//最后发送的消息
                        log_mag += "当前人物未结算，结算状态";
                        let current_action = action.action;
                        if (current_action == "打工") {//打工执行逻辑
                            let player_data = data.getData("player", player_id);
                            let Player_level_id = data.Level_list.find(item => item.level == player_data.境界).level_id;
                            let lingshi = 45 + 3 * Player_level_id;
                            let time = parseInt(action.time) / 1000 / 60;//分钟
                            let other_lingshi = 0;
                            let rand = Math.random();
                            if (rand < 0.2) {
                                rand = Math.trunc(rand * 10) + 40;
                                other_lingshi = rand * time;
                                msg.push("\n本次打工小费: "+rand * time);
                            } else if (rand > 0.8) {
                                rand = Math.trunc(rand * 10) + 5;
                                other_lingshi = -1 * rand * time;
                                msg.push("\n由于你的疏忽,货物被人顺手牵羊,老板大发雷霆,灵石减少"+rand * time);
                            }
                            let get_lingshi = lingshi * time + other_lingshi;//最后获取到的灵石
                            await this.setFileValue(player_id, get_lingshi, "灵石");//添加灵石
                            let arr = action;
                            arr.is_jiesuan = 1;
                            delete arr.group_id;//结算完去除group_id
                            await redis.set("xiuxian:player:" + player_id + ":action", JSON.stringify(arr));
                            msg.push("\n本次打工共获取"+get_lingshi+"灵石");
                            log_mag+="收入"+get_lingshi;
                            if (is_group) {
                                await this.pushInfo(push_address, is_group, msg)
                            } else {
                                await this.pushInfo(player_id, is_group, msg);
                            }

                        } else if (current_action == "闭关") {//闭关执行逻辑
                            let player_data = data.getData("player", player_id);
                            let Player_level_id = data.Level_list.find(item => item.level == player_data.境界).level_id;
                            let xiuwei = parseInt((50 + 3 * Player_level_id) * (player_data.修炼效率提升 + 1));//增加的修为
                            let blood = parseInt(player_data.血量上限 * 0.02);
                            let time = parseInt(action.time) / 1000 / 60;//分钟
                            let rand = Math.random();
                            let other_xiuwei = 0;
                            if (rand < 0.2) {
                                rand = Math.trunc(rand * 10) + 45;
                                other_xiuwei = rand * time;
                                msg.push("\n本次闭关顿悟,额外增加修为:"+rand * time);
                            } else if (rand > 0.8) {
                                rand = Math.trunc(rand * 10) + 5;
                                other_xiuwei = -1 * rand * time;
                                msg.push("\n由于你闭关时隔壁装修,导致你差点走火入魔,修为下降"+rand * time);
                            }
                            await this.setFileValue(player_id, xiuwei * time + other_xiuwei, "修为");
                            await this.setFileValue(player_id, blood * time, "当前血量");
                            let arr = action;
                            arr.is_jiesuan = 1;
                            delete arr.group_id;//结算完去除group_id
                            await redis.set("xiuxian:player:" + player_id + ":action", JSON.stringify(arr));
                            msg.push("\n闭关结束,增加修为:" + xiuwei * time, "  获得治疗,血量增加:" + blood * time);
                            if (is_group) {
                                await this.pushInfo(push_address, is_group, msg)
                            } else {
                                await this.pushInfo(player_id, is_group, msg);
                            }
                        }

                    }
                }
            }
            //输出日志
           // logger.info(log_mag);
        }
    }

    /**
     * 增加player文件某属性的值（在原本的基础上增加）
     * @param user_qq
     * @param num 属性的value
     * @param type 修改的属性
     * @returns {Promise<void>}
     */
    async setFileValue(user_qq, num, type) {
        let user_data = data.getData("player", user_qq);
        let current_num = user_data[type];//当前灵石数量
        let new_num = current_num + num;
        if (type == "当前血量" && new_num > user_data.血量上限) {
            new_num = user_data.血量上限;//治疗血量需要判读上限
        }
        user_data[type] = new_num;
        await data.setData("player", user_qq, user_data);
        return;
    }

    /**
     * 推送消息，群消息推送群，或者推送私人
     * @param id
     * @param is_group
     * @returns {Promise<void>}
     */
    async pushInfo(id, is_group, msg) {
        if (is_group) {
            await Bot.pickGroup(id)
                .sendMsg(msg)
                .catch((err) => {
                    Bot.logger.mark(err);
                });
        } else {
            await common.relpyPrivate(id, msg);
        }
    }

}


/**
 * 判断对象是否不为undefined且不为null
 * @param obj 对象
 * @returns obj==null/undefined,return false,other return true
 */
function isNotNull(obj) {
    if (obj == undefined || obj == null)
        return false;
    return true;
}